<template>
  <div>
    <div class="dis_top" style="background-color: #f2f2f2;padding: 10px;">
      <p>复检录入</p>
      <div class="selfinfo">
        <span>体检编号：{{ peOrdersMain.orderNo }}</span>
        <span>姓名：{{ peOrdersMain.customerName }}</span>
        <span>性别：{{ peOrdersMain.sex|formatSex }}</span>
        <span>年龄：{{ peOrdersMain.age }}</span>
      </div>
    </div>
    <div class="dis_flex">
      <div class="flex_l">
        <div class="l_right" style="line-height: 2em;background-color: #f2f2f2;">
          检查项目结果状态列表
          <div v-for="item in ItemList" :key="item.itemId" class="list_ch">
            <div style="margin-bottom: 15px">
              <el-checkbox label="" v-model="item.status" :checked="item.checkStatus===1" :disabled="true"></el-checkbox>
              <el-link
                  @click="onItemChange(item.itemId)"
                  :type="examItemCurId===item.itemId ? 'success':''"
                  style="margin-left: 5px"
              >
                {{ item.itemName }}
                <span style="color: red" v-if="item.errorItemContentCount>0">
                  ({{ item.errorItemContentCount }})
                </span>
              </el-link>
            </div>
          </div>
        </div>
      </div>

      <div class="flex_r">
        <!-- 右侧标签页 -->
        <div>
          <div class="r_box">
            <!--异常结果列表 -->
            <el-table
              :data="examItemContentDetails"
              style="width: 100%"
              :span-method="objectSpanMethod"
              :row-class-name="tableRowClassName"
              height="450"
              >
                <el-table-column label="项目名称" width="150" fixed>
                  <template slot-scope="scope">
                    <div :class="scope.row.normalResult?'':'red'">{{scope.row.itemName}}</div>
                  </template>
                </el-table-column>
                <el-table-column  label="检查内容" fixed>
                  <template slot-scope="scope">
                    <div :class="scope.row.normalResult?'':'red'">{{scope.row.contentName}}</div>
                  </template>
                </el-table-column>
                <el-table-column prop="resultValue" label="异常结果" fixed>
                  <template slot-scope="scope">
                    <div :class="scope.row.normalResult?'':'red'">{{scope.row.resultValue}}</div>
                  </template>
                </el-table-column>
                <el-table-column label="医生" prop="editor" width="150" fixed>
                  <template slot-scope="scope">
                    <div :class="scope.row.normalResult?'':'red'">{{scope.row.doctorName}}</div>
                  </template>
                </el-table-column>
            </el-table>

            <!--诊断结论 -->
            <div style="margin-top: 15px;background: #eee">
              <el-row>
                <el-col :span="2">
                  <el-button v-if="action==='edit'" @click="addConclusion()" style="margin: 5px 10px;">添加结论</el-button>
                </el-col>
                <el-col :span="2">
                  <el-button v-if="action==='edit'" @click="addRow" style="margin: 5px 10px;">+</el-button>
                </el-col>
                <el-col :span="20">
                  <h2 style="text-align: center;line-height: 40px">诊断结论</h2>
                </el-col>
              </el-row>
              <el-form ref="form" label-width="0px" label-position="left">
                <el-table
                    :header-cell-style="{'text-align': 'center',background: '#00FFFF','font-weight': '400',color:'#000'}"
                    :cell-style="{'margin-bottom': '0',}"
                    :data="reviewResultInfoList"
                    border
                    style="margin-top: 10px"
                >
                  <el-table-column prop="date" label="序号" width="80" type="index"></el-table-column>
                  <el-table-column label="结论及建议">
                    <template slot-scope="scope">
                      <el-form-item :prop="'reviewResultInfoList['+scope.$index+']'">
                        <el-input
                            type="textarea"
                            v-model.trim="scope.row.resultInfo"
                            size="mini"
                            placeholder="请填写值"
                            :autosize="{ minRows: 3}"
                        ></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="排序" width="180">
                    <template slot-scope="scope">
                      <el-button size="mini" @click="upindex(scope.$index,scope.row)">↑</el-button>
                      <el-button size="mini" @click="downindex(scope.$index,scope.row)">↓</el-button>

                      <el-button size="mini" @click="removeResRecord(scope.row)">-</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <div style="margin-top: 15px">
                  <el-button type="danger" v-if="action==='edit'" @click="rollback">返 检</el-button>
                </div>
                <!-- 底部签字 -->
                <div style="margin-top: 50px">
                  <el-row>
                    <el-col :span="8">
                      <el-form-item label="复检医生" label-width="100px">
                        <el-select v-model="peOrdersMain.reviewDoctorName">
                          <el-option label="admin" value="admin"></el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="复检时间" label-width="100px">
                        <el-date-picker
                            v-model="peOrdersMain.reviewTime"
                            type="datetime"
                            value-format="yyyy-MM-dd HH:mm:ss">
                        </el-date-picker>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-button type="primary" @click="listVisible=true">查看初检结论</el-button>
                      <el-button type="success" @click="viewReport">预览报告</el-button>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="8">
                      <el-form-item label="初检医生" label-width="100px">
                        <el-select v-model="peOrdersMain.verifyDoctorName" disabled>
                          <el-option label="system" value="system"></el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="初检时间" label-width="100px">
                        <el-date-picker
                            v-model="peOrdersMain.verifyTime"
                            type="datetime"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            disabled
                        >
                        </el-date-picker>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-button v-if="action==='edit'" type="primary" @click="saveRecord">提交</el-button>
                      <el-button class="buttons" @click="huitui()">返回</el-button>
                    </el-col>
                  </el-row>
                </div>
              </el-form>
            </div>
          </div>
        </div>
      </div>
    </div>

    <el-dialog title="选择诊断建议" :visible.sync="moreVisible">
      <el-form ref="form" :model="searchForm" label-width="0px" label-position="left">
        <el-row>
          <el-col :span="12">
            <el-form-item style="white-space: nowrap;" >
              <el-input class="input_c" v-model="searchForm.keyword" placeholder="请输入关键词"> clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item label="">
              <el-button type="primary" icon="el-icon-search" @click="getCommonResults"></el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table
          ref="multipleTable"
          header-row-class-name="header_row_style"
          :data="CommonResults"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="常用结果词条" prop="entryContent">
        </el-table-column>
        <el-table-column label="异常解读" prop="errorInfo">
        </el-table-column>
        <el-table-column label="健康指导" prop="healthGuid">
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addRecord">确定</el-button>
        <el-button type="primary" @click="moreVisible=false">关闭</el-button>
      </div>
    </el-dialog>

    <el-dialog title="初检结论" :visible.sync="listVisible">
      <el-table
          :header-cell-style="{'text-align': 'center',background: '#00FFFF','font-weight': '400',color:'#000'}"
          :cell-style="{'margin-bottom': '0',}"
          :data="verifyResultInfoList"
          border
          style="margin-top: 10px"
      >
        <el-table-column prop="date" label="序号" width="80" type="index"></el-table-column>
        <el-table-column label="结论及建议" prop="resultInfo"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="listVisible=false">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import {formatTimeToStr} from "@src/common/utils/date";

export default {
  data() {
    return {
      peOrdersDetailsList: [],
      resultArr: [],
      moreVisible: false,
      listVisible: false,
      CommonResults: [],
      trendOptions: [
        {label: "↑", value: 1},
        {label: "↓", value: 2},
        {label: "+", value: 3},
      ],
      peOrdersDetail: {},
      deptName: "",
      ordersId: '',
      action: '',
      userName: '',
      userId: '',
      peOrdersMain: {
        reviewTime: new Date()
      },
      examItemContentDetails: [],
      verifyResultInfoList: [],
      reviewResultInfoList: [],
      searchForm: {
        keyword: '',
        deptIds: [],
      },
      examItemCurId: '',
      ItemList: [],
      errItemIds: [],
      ItemDict: {},
      form: {
        diagnosisResult: ""
      },
    }
  },
  filters: {
    formatSex: function (val) {
      var dict = {1: "男", 2: "女"}
      return dict[val]
    },
  },
  methods: {
    objectSpanMethod({row, column, rowIndex, columnIndex}) {
      if (columnIndex === 0) {
        if(rowIndex === 0){
          return {
            rowspan: this.examItemContentDetails.length-1 ,
            colspan: 1
          };
        }else {
          if(rowIndex==this.examItemContentDetails.length-1){
            if(columnIndex == 1){
              return {
                rowspan: 3,
                colspan: 1
              };
            }
            return {
              rowspan: 1,
              colspan: 1
            };
          }else {
            return {
              rowspan: 0,
              colspan: 0
            };
          }
        }
      }
    },
    tableRowClassName({row, rowIndex}) {
      if(rowIndex===this.examItemContentDetails.length-1){
        return 'success-row';
      }
      return '';
    },

    getPeExamRecordDetail() {
      this.$axios.getReviewPeOrdersMainDetails({
        ordersId: this.ordersId,
      }).then(res => {
        if (res.code === "00000") {
          const peOrdersDetailsList = res.data.peOrdersDetailsList;
          peOrdersDetailsList.forEach((item, index) => {
            this.ItemDict[item.itemId] = item
            this.ItemList.push({
              itemId: item.itemId,
              itemName: item.itemName,
              checkStatus: item.checkStatus,
              errorItemContentCount: item.errorItemContentCount
            })
          })
          this.peOrdersMain = res.data.peOrdersMain
          const list = this.peOrdersMain.verifyResultInfoList
          list.forEach((v,index) => {
            const obj = {
              index : index,
              itemId: v.itemId,
              deptId: v.deptId,
              resultInfo: v.resultInfo
            }
            this.verifyResultInfoList.push(obj)
            this.reviewResultInfoList.push(obj)
          })

          if (this.ItemList.length > 0) {
            this.examItemCurId = this.ItemList[0].itemId
            this.peOrdersDetail = this.ItemDict[this.ItemList[0].itemId]
            if (this.peOrdersDetail.examRecord !== null) {
              this.examItemContentDetails = this.peOrdersDetail.examItemContentDetails
              this.examItemContentDetails.forEach(v => {
                v["itemName"] = this.peOrdersDetail.itemName
                v["doctorName"] = this.peOrdersDetail.examRecord.doctorName
                v["resultValue"] = v.examContentsResult && v.examContentsResult.resultValue
              })
              this.examItemContentDetails.push({
                itemName: "科室小结",
                contentName: this.peOrdersDetail.diagnosisResult || '暂无',
                normalResult: true,
              })
            }
          }
          console.log(this.examItemContentDetails)

          const user = JSON.parse(localStorage.getItem("ms_userInfo"))
          this.peOrdersMain.reviewDoctorName = user.personName
          this.peOrdersMain.reviewTime = formatTimeToStr(new Date(), "yyyy-MM-dd hh:mm:ss")
        }
      })
    },

    onItemChange(id) {
      this.examItemCurId = id
      this.peOrdersDetail = this.ItemDict[this.examItemCurId]
      this.peOrdersDetail.doctorCode = this.userId
      this.peOrdersDetail.doctorName = this.userName
      if (this.peOrdersDetail.examRecord !== null) {
        this.examItemContentDetails = [...this.peOrdersDetail.examItemContentDetails]
        this.examItemContentDetails.forEach(v => {
          v["itemName"] = this.peOrdersDetail.itemName
          v["doctorName"] = this.peOrdersDetail.examRecord.doctorName
          v["resultValue"] = v.examContentsResult && v.examContentsResult.resultValue
        })
        this.examItemContentDetails.push({
          itemName: "科室小结",
          contentName: this.peOrdersDetail.diagnosisResult,
          normalResult: true,
        })
      }
    },
    addConclusion() {
      this.moreVisible = true;
      this.getCommonResults()
    },
    getCommonResults() {
      this.searchForm.deptIds = [this.peOrdersDetail.deptId]
      this.$axios.queryResultPage(this.searchForm).then(res => {
        if (res.code === "00000") {
          this.CommonResults = res.data.records
        }
      })
    },

    handleSelectionChange(val) {
      this.multipleTablelist = val;
    },

    addRecord() {
      this.multipleTablelist.map(item => {
        var obj = {
          itemId: item.examItemId,
          deptId: item.deptId,
        }
        if(item.errorInfo !== null && item.errorInfo !== 'null'){
          obj['resultInfo'] =`${item.entryContent}【${item.errorInfo}】，${item.healthGuid}`
        }else {
          obj['resultInfo'] =`${item.entryContent}，${item.healthGuid}`
        }

        if(this.reviewResultInfoList=== null){
          obj['index']= 1
          this.reviewResultInfoList = [obj]
        }else {
          obj['index']= this.reviewResultInfoList.length
          this.reviewResultInfoList.push(obj)
        }
      })
      this.moreVisible = false
    },

    rollback(){
      var req = {
        ordersId: this.ordersId,
        returnCheck:true
      }
      this.$axios.saveReviewPeOrdersMainDetails(req).then(res => {
        if (res.code === "00000") {
          this.$message({
            type: 'success',
            message: res.msg
          })
        }
      })
    },

    saveRecord() {
      var req = {
        ordersId: this.ordersId,
        reviewResultInfoList: this.reviewResultInfoList,
        reviewTime: this.peOrdersMain.reviewTime,
        reviewDoctorName: this.peOrdersMain.reviewDoctorName,
      }

      this.$axios.saveReviewPeOrdersMainDetails(req).then(res => {
        if (res.code === "00000") {
          this.$message({
            type: 'success',
            message: res.msg
          })
        }
      })
    },

    huitui() {
      this.$router.go(-1)
    },

    // 上移，下移
    upindex(index, row) {
      if (index > 0) {
        let upDate = this.reviewResultInfoList[index - 1];
        this.reviewResultInfoList.splice(index - 1, 1);
        this.reviewResultInfoList.splice(index, 0, upDate);
      } else {
        this.$message.warning("已经是第一条了！");
        return false;
      }
    },

    downindex(index, row) {
      if (index + 1 === this.reviewResultInfoList.length) {
        this.$message.warning("已经是最后一条了！");
        return false;
      } else {
        let downDate = this.reviewResultInfoList[index + 1];
        this.reviewResultInfoList.splice(index + 1, 1);
        this.reviewResultInfoList.splice(index, 0, downDate);
      }
    },

    addRow() {
      this.reviewResultInfoList.push({
        index: this.reviewResultInfoList.length,
        resultInfo: ''
      })
    },

    removeResRecord(row) {
      var arr = this.reviewResultInfoList
      arr.splice(row.index, 1)
      this.reviewResultInfoList = arr
    },

    viewReport(){
      this.$axios.getPeExamReportsList({orderNo:this.ordersId}).
      then(res => {
        if (!res.success || res.data.total === 0) {
          this.$message.error("未查询到体检报告信息")
        }else {
          window.open(res.data.records[0]['reportPrintUrl'], "_blank");
        }
      })
    },

  },
  created() {
    this.ordersId = localStorage.getItem("recheck_ordersId")
    this.action = localStorage.getItem("recheck_action")
    this.getPeExamRecordDetail()
  }
}
</script>

<style scoped>
::v-deep .el-textarea__inner{
  overflow-y: hidden;
}

.red{
  color: red;
}

.dis_top {
  position: absolute;
  z-index: 99;
  top: 0px;
  left: 0px;
  padding: 5px;
  color: #000000;
  font-weight: bold;
  width: calc(100% - 10px);
  background: #ffffff;

}

.dis_top > div {
  display: flex;
  align-items: center;
}

.dis_top > div > span {
  margin-left: 20px;
}

.dis_flex {
  display: flex;
  margin-top: 90px;
}

.flex_l {
  width: 300px !important;
  flex-shrink: 0;
  margin-right: 10px;
  display: flex;
  flex-direction: column;
}

.r_box {
  margin-left: 20px;
  margin-bottom: 20px;
  width: 1300px;
  line-height: 25px;
  border: 1px solid #efefef;
}

.r_box_con {
  padding-left: 20px;
  padding-right: 20px;
}

flies_box {
  margin-left: 20px;
  margin-bottom: 20px;
  width: 1300px;
  line-height: 25px;
}

.flies {
  margin-top: 15px;
}

.flies p {
  margin-bottom: 10px;
}

.r_box_con_title {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  border-bottom: 1px solid #333;
  font-size: 18px;
  line-height: 30px;
}

.r_box_con_bor {
  border-bottom: 1px solid #333;
  padding-bottom: 10px;
}

.r_box_con_box {
  margin-top: 10px;
  display: flex;
  align-items: center;
  font-size: 15px;
  line-height: 45px;
}

.r_box_con_sl1 {
  padding: 0px 5px;
  width: 20%;
}

.r_box_con_sl2 {
  padding: 0px 5px;
  width: 30%;
}

.r_box_con_sl3 {
  padding: 0px 5px;
  width: 10%;
}

.r_box_con_sl4 {
  padding: 0px 5px;
  width: 15%;
}

.r_box_con_sl5 {
  padding: 0px 5px;
  width: 15%;
}

.r_box_con_sl6 {
  padding: 0px 5px;
  width: 10%;
}

.r_box_con_res {
  margin-top: 20px;
}

.el-form--inline .el-form-item {
  margin: 20px;
}

.textarea {
  width: 600px
}

.r_box_con_res /deep/ .el-form-item__label {
  font-size: 22px !important;
}

.r_box_con_bottom {
  margin-top: 20px;
  display: flex;
}

.r_box_con_bottom div {
  margin-right: 15px;
}

.l_left {
  color: #7F7F7F;
  font-weight: bold;
  height: 36px;
}

.list_ch {

}

.flex_r {
  background: #ffffff;
   overflow-y: scroll;
}

.r_list {
  display: flex;
  justify-content: space-between;
  align-items: center;
  line-height: 30px;
  color: #666666;
}

.r_list:hover {
  color: #2F9688;
  font-weight: bold;
}

.l_right {
  background: #F2F2F2;
  height: 100%;
  padding: 10px;
}


.diagnose > div:first-child {
  display: flex;
}

.bj_doctor {
  background: #E5F6FE;
}

.selfinfo {
  padding: 20px;
  background-color: #E5F6FE;
}

.selfinfo span {
  margin-right: 20px;
}
</style>
